package club.pinea.handler.lobby;

import club.pinea.annotations.Head;
import club.pinea.interfaces.TCPMessage;
import club.pinea.model.Seat;
import club.pinea.proto.BasicProto;
import club.pinea.proto.CommandProto;
import club.pinea.proto.LobbyProto;
import club.pinea.send.MessageSend;
import club.pinea.service.SeatService;
import club.pinea.service.UserService;
import club.pinea.session.GlobalServerPlayerContainer;
import club.pinea.session.IOSession;
import club.pinea.session.ServerPlayer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/**
 * @description: 离开座位handler
 * @author: 华上进
 * @createTime: 2021/6/29 17:02
 */
@Head(CommandProto.Command.C_S_LEAVE_ROOM_VALUE)
@Component
public class LeaveSeatHandler implements TCPMessage<BasicProto.BaseMessage> {

    /**
     * redis座位操作服务类
     */
    @Autowired
    private SeatService seatService;

    /**
     * 用户操作服务类
     */
    @Autowired
    private UserService userService;


    /**
     * 当前用户是否坐在某个座位上
     */
    private Seat seat;


    @Override
    public void doMessage(BasicProto.BaseMessage msg, IOSession session) throws Exception {
        LobbyProto.LeaveSeatRequest request = LobbyProto.LeaveSeatRequest.parseFrom(msg.getBody());
        ServerPlayer serverPlayer = GlobalServerPlayerContainer.getServerPlayer(session);
        //将该座位制空
        int seatId = request.getSeatNum();
        seat = seatService.getSeatBean(seatId, serverPlayer.getRoom());
        seat.setSeatStatus(0);
        seat.setSeatUser(null);
        seatService.updateSeat(seat, seatId, true, serverPlayer.getRoom());//更新数据库中的座位信息状态
        seat = null;//将当前连接状态中的坐状态设置为正在坐
        int userId = request.getUserId();

        LobbyProto.LeaveSeatResponse response = LobbyProto.LeaveSeatResponse.newBuilder()
                .setMoney(userService.getMoneyById(userId))
                .setRes(MessageSend.successRes())
                .build();
        // 返回消息
        MessageSend.sendToUser(response, session);
    }


}
